package sunlight.logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import sunlight.util.TheTime;

public class RemoteEventLogger implements EventLogger {
//TODO work in progress....	
	protected Socket 	  socketConnection;
	protected InetAddress Host;
	protected String	  END_COMMUNICATION_NOTIFIER = "COMMUNICATION_END";
	
	public String Address;
	public int 	  Port;
	
	protected PrintWriter log;
	
	public RemoteEventLogger() throws IOException {
		this.Port 	 = 1987;
		this.Address = "localhost";
		
		this.open();
	}
	
	public RemoteEventLogger(String address) throws IOException{
		this.Port 	 = 1987;
		this.Address = address;
		
		this.open();
	}
	
	public RemoteEventLogger(String address, int port) throws IOException{
		this.Port	 = port;
		this.Address = address;
		
		this.open();
	}

	@Override
	public void open() throws IOException {
		try {
			this.Host = InetAddress.getByName(this.Address);
		
			this.socketConnection = new Socket(this.Host, this.Port);
		
			this.log = new PrintWriter(this.socketConnection.getOutputStream());
		
			//this.socketConnection.setKeepAlive(true);
			
			this.init();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	
	public void write(String message, String type){
		
		String date = TheTime.now(DATE_FORMAT);
		String time = TheTime.now(TIME_FORMAT);
		
		String line = new String(LOG_FORMAT);
			   
		line = line.replaceAll("<date>", date);
		line = line.replaceAll("<time>", time);
		line = line.replaceAll("<message>", message);
		line = line.replaceAll("<type>", type);
			
		this.log.println(line);	
		this.log.flush();
	}

	@Override
	public void close() {
		
		this.write("___________Aplicatia a fost oprita______________", MESSAGE);
		
		this.log.println(this.END_COMMUNICATION_NOTIFIER);	
		this.log.flush();
		
		try {
			this.log.close();
			this.socketConnection.close();
		} catch (IOException e) {
			;
		}
		
	}

	@Override
	public void delete(String logname) {
		// TODO Auto-generated method stub
	}

	@Override
	public void init() {
		this.write("___________Aplicatia a fost pornita_____________", MESSAGE);
	}

}
